// pages/vip/buy.js

const app = getApp()
Page({

     /**
      * 页面的初始数据
      */
	data: {
		userInfo: {},
		vipInfo: {},
		isVip: false,
		startTime: '',
		endTime: '',
		shade:"none"
	},
     /**
      * 生命周期函数--监听页面加载
      */
	onLoad: function (options) {
		let that = this;
		let nowTime = Math.round(new Date().getTime() / 1000).toString();
		
		app.login(function(userInfo){

			that.setData({
				userInfo: userInfo.data
			})
			//查询是否是vip了
			if (userInfo.data.vipEndTime > nowTime || userInfo.data.vipEndTime == 'ever') {
				that.setData({
					isVip: true
				});
				if (userInfo.data.vipEndTime != 'ever') {
					that.setData({
						startTime: app.format(userInfo.data.vipStartTime),
						endTime: app.format(userInfo.data.vipEndTime)
					});
				}
			} else {
				that.setData({
					isVip: false
				});
			}
		});
	
		
		app.connect('vipInfo', {}, function (options) {
			that.setData({
				vipInfo: options
			});
		});
	
	},
	
     /**
      * 生命周期函数--监听页面初次渲染完成
      */
	onReady: function () {
	
	},

     /**
      * 生命周期函数--监听页面显示
      */
	onShow: function () {

	},

     /**
      * 生命周期函数--监听页面隐藏
      */
	onHide: function () {

	},

     /**
      * 生命周期函数--监听页面卸载
      */
	onUnload: function () {

	},

     /**
      * 页面相关事件处理函数--监听用户下拉动作
      */
	onPullDownRefresh: function () {

	},

     /**
      * 页面上拉触底事件的处理函数
      */
	onReachBottom: function () {

	},

     /**
      * 用户点击右上角分享
      */
	onShareAppMessage: function () {

	},
	//购买
	buy: function (options) {
		let that = this;
		var id = options.target.dataset.id;
		//发起支付-创建订单
		app.connect('buy/index', {
			vipName: that.data.vipInfo[id].name,
			price: that.data.vipInfo[id].price,
			vipTime: that.data.vipInfo[id].time,
			uid: that.data.userInfo.uid
		}, function (res) {
			console.log(res);
			var order_id = parseInt(res);
			app.connect('buy/wxpay', {
				money: that.data.vipInfo[id].price,
				orderid: res.data,
				openid: that.data.userInfo.openId
			}, function (e) {
		
				//小程序唤起支付
				var prepay_id = e.prepay_id;
			
				wx.requestPayment({
					timeStamp: e.timeStamp, //时间
					nonceStr: e.nonce_str, //随机字符创
					package: "prepay_id=" + e.prepay_id,
					signType: "MD5",
					paySign: e.sign,
					success: function (e) {

						console.log(e);
						//成功后处理
						app.connect("buy/paySuccess", {
							order_id: order_id
						}, function (e) {
						
							wx.showLoading({
								title: '加载中'
							})
							app.getUserInfo();
							
							setTimeout(function(){
								wx.hideLoading();
								that.onLoad();	
							},2000);
						});

					},
					fail: function (e) {
						app.getUserInfo();
						that.onLoad();	
					}
				});
			});
		});
	},
	showKeFu:function(){
		var shade = this.data.shade;
		console.log(shade);
		if(shade == 'none') {
			this.setData({
				shade:'block'
			})
		}else{
			this.setData({
				shade: 'none'
			})
		}
	}
})